package com.xin.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xin.constant.RedisConstant;
import com.xin.dao.SetmealDao;
import com.xin.entity.PageResult;
import com.xin.pojo.Setmeal;
import com.xin.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 夜天
 * @Date 2021/12/16 11:27
 * @Version 1.0.0
 * @description： 套餐服务实现类
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;
    // 新增套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer id = setmeal.getId();
        // 调用setSetMealAndCheckGroup()方法
        this.setSetMealAndCheckGroup(id,checkgroupIds);
        // 将图片名称保存到Redis
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }
    //生成套餐详情静态页面（多个）
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateFTLHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",
                    dataMap);
        }
    }
    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String,Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList",setmealList);
        this.generateFTLHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }

    // 用于生成静态ftl页面
    public void generateFTLHtml(String templateName,String HtmlPageName,Map<String,Object> map){
        // 获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模板
            Template template = configuration.getTemplate(templateName);
            // 写入数据，指定路径
            File WriteFile = new File(outPutPath + "/"+ HtmlPageName);
            // 输出流
            out = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(WriteFile)));
            // 输出文件
            template.process(map,out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    // 分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }
    // 查询所有套餐
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }
    // 根据 id 查询套餐数据
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    // 设置套餐和检查组多对多关系
    public void setSetMealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
            }
        }
    }
}
